#!/user/bin/env python3
# -*- coding: utf-8 -*-

import requests
import json
from math import sqrt

"""
读写文本文件：
    将1-99之间的素数保存到a文件中，
    100-999的素数保存到b文件中，
    1000-9999的素数保存到c文件中。
"""


def keep_prime():
    def is_prime(n):
        assert n > 0
        for factor in range(2, int(sqrt(n) + 1)):
            if n % factor == 0:
                return False
        return True if n != 1 else False

    filenames = ('a.txt', 'b.txt', 'c.txt')
    fs_list = []
    try:
        for filename in filenames:
            fs_list.append(open(filename, 'w', encoding='utf-8'))
        for num in range(1, 10000):
            if is_prime(num):
                if num < 100:
                    fs_list[0].write(str(num) + '\n')
                elif num < 1000:
                    fs_list[1].write(str(num) + '\n')
                else:
                    fs_list[2].write(str(num) + '\n')
    except IOError as ex:
        print(ex)
        print("写文件时发生错误!")
    finally:
        for fs in fs_list:
            fs.close()
    print("操作完成")


# keep_prime()


"""读写二进制文件"""


def copy_photo():
    try:
        with open('ball.png', 'rb') as fs1:
            data = fs1.read()
            print(type(data))  # <class 'bytes>
        with open('3.jpg', 'wb') as f2:
            f2.write(data)
    except FileNotFoundError:
        print("指定的文件无法打开")
    except IOError:
        print("读写文件时发生错误")
    print("程序执行结束")


# copy_photo()


def keep_json():
    my_dict = {
        'name': '陆军',
        'age': 38,
        'qq': 78974223,
        'friends': ['王大锤', '白远方'],
        'cars': [
            {'brand': 'BYD', 'max_speed': 180},
            {'brand': 'Audi', 'max_speed': 280},
            {'brand': 'Benz', 'max_speed': 320}
        ]
    }
    try:
        with open('data.json', 'w', encoding='utf-8') as fs:
            json.dump(my_dict, fs)
    except IOError as e:
        print(e)
    print('保存数据完成！')


# keep_json()


def json_to_py():
    res = requests.get('https://api.tianapi.com/guonei/?key=APIKey&num=10')  # 目前已失效
    data_model = json.loads(res.text)
    for news in data_model['newscast']:
        print(news['title'])
